package com.konsung.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.konsung.bean.CheckData;
import com.konsung.bean.PatientBean;
import com.konsung.bean.QueryHealthFile;
import com.konsung.greendaoUtil.DBUtitl;
import com.konsung.greendaoUtil.GreenDaoManager;
import com.konsung.greendaoUtil.PatientBeanDao;
import com.konsung.healthfile.R;
import com.konsung.kslibrary.base.BaseActivity;
import com.konsung.kslibrary.base.MvpView;
import com.konsung.network.RequestUtils;
import com.konsung.network.URLManage;
import com.konsung.network.UploadData;
import com.konsung.presenter.AddPatientPresenter;
import com.konsung.presenter.impl.AddPatientPresenterImpl;
import com.konsung.provide.ProviderReader;
import com.konsung.ui.adapter.SpinnerAdapter;
import com.konsung.ui.adapter.SwitchPatientListAdapter;
import com.konsung.util.BroadcastUtils;
import com.konsung.util.IdCardUtil;
import com.konsung.util.JsonUtil;
import com.konsung.util.ToastUtils;
import com.konsung.util.UiUtils;
import com.konsung.util.constant.GlobalConstant;
import com.loopj.android.http.TextHttpResponseHandler;
import com.synjones.bluetooth.BmpUtil;
import com.zkteco.android.IDReader.IDPhotoHelper;
import com.zkteco.android.IDReader.WLTService;

import org.apache.http.Header;
import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 新增居民和切换居民的弹窗
 */
public class AddPatientActivity extends BaseActivity<AddPatientPresenterImpl> implements
        AddPatientPresenter.View, MvpView {

    @BindView(R.id.tv_switch_patient)
    TextView tvSwitchPatient;
    @BindView(R.id.tv_add_patient)
    TextView tvAddPatient;
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.tv_idcard)
    EditText etIdcard;
    @BindView(R.id.et_contact)
    EditText etContact;
    @BindView(R.id.et_age)
    EditText etAge;
    @BindView(R.id.sp_sex)
    Spinner spSex;
    @BindView(R.id.sp_patient_type)
    Spinner spPatientType;
    @BindView(R.id.sp_blood_type)
    Spinner spBloodType;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.tv_add_line)
    TextView tvAddLine;
    @BindView(R.id.tv_switch_line)
    TextView tvSwitchLine;
    @BindView(R.id.et_query_condition)
    EditText etQuery;
    @BindView(R.id.iv_query)
    ImageView ivQuery;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.ll_add_layout)
    LinearLayout llAddLayout;
    @BindView(R.id.ll_switch_layout)
    LinearLayout llSwitchLayout;
    @BindView(R.id.btn_ok)
    TextView btnOk;
    @BindView(R.id.lv_select_patient)
    ListView lvSelectPatient;
    @BindView(R.id.iv_head_icon)
    ImageView ivHeadIcon;

    boolean idCardCheckout; //身份证是否强校验
    List<PatientBean> patientBeanList; //查询出来的数据集
    SwitchPatientListAdapter adapter; //查询集合的设配器
    private boolean isConnected;
    private boolean isCompleted;
    private String bmpStr = ""; //头像名称
    private String headBmpStr = ""; //头像字符串
    //头像位图
    private Bitmap bitmap = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(0, 0);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_patient);
        ButterKnife.bind(this);
        //默认键盘不弹出
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initReceiver();
    }

    @Override
    protected void onStart() {
        overridePendingTransition(0, 0);
        super.onStart();
        initBindEvent();
        initViewData();
        Intent intent = getIntent();
        if (intent != null && intent.getIntExtra(GlobalConstant.FLAG, -1) == 1) {
            onClick(tvSwitchPatient);
        } else {
            onClick(tvAddPatient);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        BroadcastUtils.sendDarkForStartManage();
        BroadcastUtils.sendShowAddPatient();
        Intent intent = getIntent();
        if (intent != null) {
            String idcard = intent.getStringExtra(GlobalConstant.IDCARD);
            String name = intent.getStringExtra(GlobalConstant.NAME);
            String address = intent.getStringExtra(GlobalConstant.ADDRESS);
            byte[] headPicArr = intent.getByteArrayExtra(GlobalConstant.PICTURE);
            if (!TextUtils.isEmpty(idcard)) {
                //头像用Base64保存
                headBmpStr = Base64.encodeToString(headPicArr, Base64.DEFAULT);
                //头像命名以身份证号命名，唯一性
                bmpStr = idcard;
                //保存头像到本地
                if (headPicArr != null && headPicArr.length > 0) {
                    byte[] buf = new byte[WLTService.imgLength];
                    if (1 == WLTService.wlt2Bmp(headPicArr, buf)) {
                        bitmap = IDPhotoHelper.bgr2Bitmap(buf);
                        BmpUtil.saveBitmap(bitmap, bmpStr);
                    }
                }
                if (bitmap != null) {
                    ivHeadIcon.setImageBitmap(bitmap);
                }
                etIdcard.setText(idcard);
                etName.setText(name);
                etAddress.setText(address);
                List<PatientBean> patientBeen = DBUtitl.queryIdCard(this, idcard);
                if (patientBeen.size() > 0) {
                    addPatientBeanResult(AddState.EXIST);
                }
            }
        }
    }

    /**
     * 注册广播
     */
    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(BroadcastUtils.HEALRH_MEASURE_CARD_READER);
        filter.addAction(BroadcastUtils.CARD_READER);
        registerReceiver(usbStateReceiver, filter);
    }

    /**
     * 绑定点击事件
     */
    private void initBindEvent() {
        btnOk.setOnClickListener(this);
        ivClose.setOnClickListener(this);
        ivClear.setOnClickListener(this);
        ivQuery.setOnClickListener(this);
        tvAddPatient.setOnClickListener(this);
        tvSwitchPatient.setOnClickListener(this);
        String digits = "0123456789xX"; //弹出数字框，且限制编辑框输入内容
        etIdcard.setKeyListener(DigitsKeyListener.getInstance(digits));
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String idCard = etIdcard.getText().toString();
                String name = etName.getText().toString();
                if (idCard.length() != 18) {
                    btnOk.setEnabled(false);
                } else {
                    if (idCardCheckout) { //强校验

                        String msg = IdCardUtil.idCardValidate(idCard);
                        if (msg.length() != 0) { //身份证号码不合法
                            btnOk.setEnabled(false);
                            ToastUtils.showShortToast(R.string.idcard_error1);
                        } else { //身份证号码合法

                            btnOk.setEnabled(true);
                        }
                    } else { //不校验身份证号码
                        btnOk.setEnabled(true);
                    }
                    //TODO 差居民类型
                    int ageFormIdCard = IdCardUtil.getAgeFormIdCard(idCard);
                    etAge.setText(ageFormIdCard + ""); //设置年龄
                    int sexFormIdCard = IdCardUtil.getSexFormIdCard(idCard); // 1男2女
                    spSex.setSelection(sexFormIdCard - 1);
                }
                if (TextUtils.isEmpty(name)) {
                    btnOk.setEnabled(false);
                }
            }
        };
        etIdcard.addTextChangedListener(watcher);
        etName.addTextChangedListener(watcher);
        etIdcard.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String idCard = etIdcard.getText().toString();
                if (!hasFocus) {
                    if (idCard.length() > 0) {
                        if (idCardCheckout) {
                            if (IdCardUtil.idCardValidate(idCard).length() > 0) {

                                ToastUtils.showShortToast(R.string.idcard_error1);
                            }
                        } else {
                            if (idCard.length() != 18) {
                                ToastUtils.showShortToast(R.string.idcard_error1);
                            }
                        }
                    }
                } else {
                }
            }
        });

        lvSelectPatient.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PatientBean patientBean = patientBeanList.get(position);
                UiUtils.setCurrentPatient(patientBean.getIdcard());
                ToastUtils.showShortToast(R.string.set_success);
                BroadcastUtils.sendDismissAddPatient();
                finish();
            }
        });
    }

    /**
     * 初始化界面数据
     */
    private void initViewData() {
        idCardCheckout = ProviderReader.getIdCardCheckout(AddPatientActivity.this);

        String[] bloodType = UiUtils.getStringArr(R.array.blood_type);
        SpinnerAdapter bloodTypeAdapter = new SpinnerAdapter(this, bloodType);
        spBloodType.setPopupBackgroundDrawable(UiUtils.getDrawable(R.drawable.bg_drop_down_box));
        spBloodType.setAdapter(bloodTypeAdapter);

        String[] sexType = UiUtils.getStringArr(R.array.sex_type);
        SpinnerAdapter sexTypeAdapter = new SpinnerAdapter(this, sexType);
        spSex.setPopupBackgroundDrawable(UiUtils.getDrawable(R.drawable.bg_drop_down_box));
        spSex.setAdapter(sexTypeAdapter);
        spSex.setSelection(2); //默认显示未知性别

        String[] patientType = UiUtils.getStringArr(R.array.patient_type);
        SpinnerAdapter patientTypeAdapter = new SpinnerAdapter(this, patientType);
        spPatientType.setPopupBackgroundDrawable(UiUtils.getDrawable(R.drawable.bg_drop_down_box));
        spPatientType.setAdapter(patientTypeAdapter);

        patientBeanList = new ArrayList<>();
        adapter = new SwitchPatientListAdapter(this, patientBeanList);
        lvSelectPatient.setAdapter(adapter);
    }

    @Override
    public AddPatientPresenterImpl initPresenter() {
        return new AddPatientPresenterImpl();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_add_patient:
                ivHeadIcon.setVisibility(View.VISIBLE);
                llSwitchLayout.setVisibility(View.GONE);
                tvSwitchLine.setVisibility(View.GONE);
                tvSwitchPatient.setTextColor(getResources().getColor(R.color.text_content));
                llAddLayout.setVisibility(View.VISIBLE);
                tvAddLine.setVisibility(View.VISIBLE);
                tvAddPatient.setTextColor(getResources().getColor(R.color.dialog_title));

                break;
            case R.id.tv_switch_patient:
                ivHeadIcon.setVisibility(View.GONE);
                llAddLayout.setVisibility(View.GONE);
                tvAddLine.setVisibility(View.GONE);
                tvSwitchPatient.setTextColor(getResources().getColor(R.color.dialog_title));
                llSwitchLayout.setVisibility(View.VISIBLE);
                tvSwitchLine.setVisibility(View.VISIBLE);
                tvAddPatient.setTextColor(getResources().getColor(R.color.text_content));
                if (patientBeanList != null && patientBeanList.size() == 0) {
                    patientBeanList.addAll(presenter.queryAllPatient());
                    adapter.notifyDataSetChanged();
                }
                break;
            case R.id.btn_ok:
                String name = etName.getText().toString();
                if (UiUtils.legalName(name) || name.trim().length() == 0) {

                    ToastUtils.showShortToast(R.string.name_not_legal);
                    return;
                }

                String idcard = etIdcard.getText().toString();
                if (idcard.length() != 18) {
                    ToastUtils.showShortToast(R.string.idcard_error1);
                    return;
                }
                String contact = etContact.getText().toString();
                int age = Integer.valueOf(etAge.getText().toString().length() == 0 ? "-1" : etAge
                        .getText().toString());
                if (age < 0 || age > 300) {
                    ToastUtils.showShortToast(R.string.age_not_legal);
                    return;
                }
                int sex = spSex.getSelectedItemPosition();
                int patientType = spPatientType.getSelectedItemPosition();
                int bloodType = spBloodType.getSelectedItemPosition();
                Date birthday = IdCardUtil.getAgeForIdCard(idcard);
                String address = etAddress.getText().toString();
                final PatientBean patientBean = new PatientBean();
                patientBean.setName(name);
                patientBean.setIdcard(idcard);
                patientBean.setContact(contact);
                patientBean.setAge(age);
                patientBean.setBirthday(birthday.getTime());
                patientBean.setBmpStr(bmpStr);
                patientBean.setHeadBmpStr(headBmpStr);
                patientBean.setAddDate(System.currentTimeMillis());
                if (sex == 0) {
                    patientBean.setSex(1);
                } else if (sex == 1) {
                    patientBean.setSex(2);
                } else {
                    patientBean.setSex(0);
                }
                patientBean.setPatientType(patientType);
                patientBean.setBlood(bloodType);
                patientBean.setAddress(address);
                //沭阳的才去查询是否建档
                if (UiUtils.isShuYangArea() && UiUtils.isConnectNetWork(MyApplication
                        .getContext())) {
                    //查询健康档案是否存在
                    final PatientBeanDao patientDao = GreenDaoManager
                            .getPatientDao(AddPatientActivity.this);
                    CheckData checkData = ProviderReader.getCheckData(this);
                    if (checkData == null) {
                        presenter.addPatient(patientBean);
                        return;
                    }
                    UiUtils.postLongThread(new Runnable() {
                        @Override
                        public void run() {
                            UiUtils.showProgress(MyApplication.getContext(), getString(R.string
                                    .search_file));
                            QueryHealthFile healthFile = new QueryHealthFile();
                            healthFile.setIdnumber(patientBean.getIdcard());
                            healthFile.setSelfname(patientBean.getName());
                            UploadData uploadData = new UploadData(AddPatientActivity.this);
                            try {
                                StringEntity stringEntity = new StringEntity(JsonUtil
                                        .toJson(healthFile), "utf-8");
                                RequestUtils.clientPost(MyApplication.getContext(),
                                        URLManage.getInstance().healthfileport,
                                        stringEntity, new TextHttpResponseHandler() {

                                            @Override
                                            public void onFailure(int statusCode, Header[]
                                                    headers,
                                                    String responseString, Throwable
                                                    throwable) {
                                                Log.d("test", "fail");
                                            }

                                            @Override
                                            public void onSuccess(int statusCode, Header[]
                                                    headers,
                                                    String responseString) {
                                                Log.d("test", "success");
                                                patientBean.setIsOtherNetSuccess(true);
                                                if (responseString != null) {
                                                    JsonObject jsonObject = new JsonParser()
                                                            .parse(responseString)
                                                            .getAsJsonObject();
                                                    int resultCode = jsonObject
                                                            .get("resultCode")
                                                            .getAsInt();
                                                    if (resultCode == GlobalConstant
                                                            .HTTP_SUCCESS) {
                                                        //有档案
                                                        patientBean.setIsFileCreat(true);
                                                    } else if (resultCode == GlobalConstant
                                                            .HTTP_NO_HAVE) {
                                                        //没有档案
                                                        ToastUtils.showLongToastSafe(getString(R
                                                                .string.user_not_creatfile));
                                                    } else {
                                                        //请求失败
                                                        patientBean.setIsOtherNetSuccess(false);
                                                    }

                                                }
                                            }
                                        });
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            try {
                                Thread.sleep(300);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            UiUtils.hideProgress();
                            Log.d("test", "main");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    presenter.addPatient(patientBean);
                                }
                            });
                        }
                    });
                } else {
                    presenter.addPatient(patientBean);
                }

                break;
            case R.id.iv_close:
                UiUtils.hideKeyboard(etName);
                BroadcastUtils.sendDismissAddPatient();
                finish();
                break;
            case R.id.iv_clear:
                etQuery.setText("");
                break;
            case R.id.iv_query:
                List<PatientBean> patientBeen = presenter
                        .queryPatient(etQuery.getText().toString());
                patientBeanList.clear();
                patientBeanList.addAll(patientBeen);
                adapter.notifyDataSetChanged();
                if (patientBeanList.size() == 0) {
                    ToastUtils.showShortToast(R.string.select_empty);
                } else {

                    ToastUtils.showShortToast(R.string.select_success);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void addPatientBeanResult(AddState sate) {
        switch (sate) {
            case SUCCESS:
                UiUtils.setCurrentPatient(etIdcard.getText().toString());
                ToastUtils.showShortToastSafe(R.string.save_success);
                BroadcastUtils.sendAddPatientSuccess();
                BroadcastUtils.sendDismissAddPatient();
                finish();
                break;
            case FAILURE:
                ToastUtils.showShortToastSafe(R.string.save_failure);
                break;
            case EXIST:
                ToastUtils.showShortToastSafe(R.string.local_exist);
                onClick(tvSwitchPatient);
                etQuery.setText(etIdcard.getText());
                patientBeanList.clear();
                patientBeanList.addAll(presenter.queryPatient(etIdcard.getText()
                        .toString()));
                adapter.notifyDataSetChanged();

                break;
            default:
                break;
        }
    }

    /**
     * 获取信息更新view
     * @param name 姓名
     * @param idcard 身份证
     * @param sex 性别
     * @param type 类型
     * @param address 地址
     * @param headPic 头像字节数组
     */
    public synchronized void getInfoFromCard(String name, String idcard, int
            sex, int type, String address, byte[] headPic) {
        //查询数据库是否存在该身份证
        List<PatientBean> list = presenter.queryIdCard(idcard);
        //存在
        if (list.size() > 0) {
            onClick(tvSwitchPatient);
            patientBeanList.clear();
            patientBeanList.addAll(list);
            adapter.notifyDataSetChanged();
        } else {
            onClick(tvAddLine);
            etName.setText(name);
            etIdcard.setText(idcard);
            //TODO 差居民类型
            int ageFormIdCard = IdCardUtil.getAgeFormIdCard(idcard);
            etAge.setText(ageFormIdCard + ""); //设置年龄
            if (ageFormIdCard == 0) {
                // 婴儿
                spPatientType.setSelection(2);
            }
            int sexFormIdCard = IdCardUtil.getSexFormIdCard(idcard); // 1男2女3未知
            spSex.setSelection(sexFormIdCard - 1);
            etAddress.setText(address);
            //头像用Base64保存
            headBmpStr = Base64.encodeToString(headPic, Base64.DEFAULT);
            if (!TextUtils.isEmpty(idcard)) {
                //头像命名以身份证号命名，唯一性
                bmpStr = idcard;
                //保存头像到本地
                if (headPic != null && headPic.length > 0) {
                    byte[] buf = new byte[WLTService.imgLength];
                    if (1 == WLTService.wlt2Bmp(headPic, buf)) {
                        bitmap = IDPhotoHelper.bgr2Bitmap(buf);
                        BmpUtil.saveBitmap(bitmap, bmpStr);
                    }
                }
                if (bitmap != null) {
                    ivHeadIcon.setImageBitmap(bitmap);
                }
            }
        }
        isCompleted = true;
    }

    /**
     * 监听usb接入的广播
     */
    private BroadcastReceiver usbStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //usb连接
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {

            } else if (BroadcastUtils.HEALRH_MEASURE_CARD_READER.equals(action)) {
                String idcard = intent.getStringExtra(GlobalConstant.IDCARD);
                String name = intent.getStringExtra(GlobalConstant.NAME);
                String address = intent.getStringExtra(GlobalConstant.ADDRESS);
                byte[] headPic = intent.getByteArrayExtra(GlobalConstant.PICTURE);
                getInfoFromCard(name, idcard, 0, 0, address, headPic);
            } else if (BroadcastUtils.CARD_READER.equals(action)) {
                String idcard = intent.getStringExtra(GlobalConstant.IDCARD);
                String name = intent.getStringExtra(GlobalConstant.NAME);
                String address = intent.getStringExtra(GlobalConstant.ADDRESS);
                byte[] headPic = intent.getByteArrayExtra(GlobalConstant.PICTURE);
                if (etIdcard != null && !etIdcard.getText().toString().equals(idcard)) {
                    getInfoFromCard(name, idcard, 0, 0, address, headPic);
                }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 4) { //F1
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();
        BroadcastUtils.sendNormalForStartManage();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (usbStateReceiver != null) {
            unregisterReceiver(usbStateReceiver);
        }
    }

    /**
     * 添加居民是否成功枚举
     */
    public enum AddState {
        SUCCESS,
        //添加成功
        FAILURE,
        //添加失败
        EXIST //本地已存在
    }
}
